package jk.spider.core.throttle.impl;

import jk.spider.core.throttle.Throttle;

public class DistributedLoadThrottleImpl implements Throttle {

	protected int milliseconds;
	protected long lastAllow;

	public DistributedLoadThrottleImpl(int milliseconds) {
		this.milliseconds = milliseconds;
		lastAllow = System.currentTimeMillis() - milliseconds;
	}

	public synchronized void throttle() {
		long thisTime = System.currentTimeMillis();
		long scheduledTime = lastAllow + milliseconds;

		if (scheduledTime > thisTime) {
			try {
				Thread.sleep(scheduledTime - thisTime);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}

		lastAllow = System.currentTimeMillis();
	}
}
